#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import web
import re
import codecs

from bs4 import BeautifulSoup
import sqlite3dbm
from mako.template import Template

from generator import * 

from bottlenose import api
AMAZON_API = api.Amazon(AWS_KEY, SECRET_KEY, ASSOCIATE_TAG, Region="JP")

#from beaker.cache import CacheManager
#from beaker.util import parse_cache_config_options
#
#cache_opts = {
#    'cache.type': 'file',
#    'cache.data_dir': PANEO_SITE_DATA_DIR + '/_paneo_data/_tmp/cache/data',
#    'cache.lock_dir': PANEO_SITE_DATA_DIR + '/_paneo_data/_tmp/cache/lock'
#}
#cache = CacheManager(**parse_cache_config_options(cache_opts))

__all__ = [
            'PaneoImage',
            'GenerateHtmlTemplate',
            'GenerateCssTemplate',
]

#@cache.cache(expire=300)
def GetAmazonItem( i ):
    feature = ""
    for f in i.findAll("feature"):
        feature = feature + f.string + "\n"
    item = {
    'associate':    ASSOCIATE_TAG, 
    'asin':         i.find('asin').string if i.find('asin') else "",
    'title':        i.find('title').string if i.find('title') else "",
    'content':      i.find('content').string if i.find('content') else "",
    'availability': i.find('availability').string if i.find('availability') else "",
    'price':        i.find('price').find('amount').string if i.find('price').find('amount') else "",
    'label':        i.find('label').string if i.find('label') else "",
    'binding':      i.find('binding').string if i.find('binding') else "",
    'brand':        i.find('brand').string if i.find('brand') else "",
    'feature':      feature,
    'imagesets':    i.find('imagesets'),
    }
    return item 

def GetImageWidth( x ):
    ua = web.ctx.env['HTTP_USER_AGENT'].lower()
    if ua.find('paneo') != -1:
        return 0 
    if ua.find('iphone') != -1:
        x = 640 
    elif ua.find('ipod') != -1:
        x = 640
    elif ua.find('android') != -1:
        x = 640 
    elif ua.find('ipad') != -1:
        x = 1280 
    else:
        x = 1536 
    return x

def ImageTagConvert( k , x , img , f , paneo_max_width , bs ):
    ext = f.get('ext')
    if os.path.exists(PANEO_SITE_DATA_DIR+'img/'+k) :
        if ext.get('src_on') == False :
            if IMG_CONV :
                if os.path.exists( PANEO_SITE_DATA_DIR + '/_tmp/cache/img/%s_%s' % ( k, x ) ):
                    img["src"] = "/" + PANEO_SITE_DIR + "/_tmp/cache/img/%s_%s" % ( k, x )
                else:
                    if paneo_max_width :
                        img["src"] = "/img/%s/%s/" % ( k , paneo_max_width )
                    else:
                        img["src"] = "/img/" + k
            else:
                img["src"] = "/" + PANEO_SITE_DIR + "/img/" + k
        else:
            if ext :
                img["src"] = ext.get('src') 
    else:
        if ext.get('src_on') == True:
            img["src"] = ext.get('src') 
    #if img["src"].find("paneoimg") != -1 :
    #    img["paneofile"] = k
    img["alt"] = ext.get('alt')
    try:
        if not ext.get('alt','').find(u'画像') :
            del(img["alt"])
    except:
        pass

    """
    <figure class="paneoimg">
    <img src="" alt="">
    <figcaption></figcaption>
    </figure>
    """
    if ext.get('caption') != "" :
        figure = bs.new_tag("figure")
        parent = img.parent
        if not "paneoimg" in img.parent.get('class',[]):
            figure["class"] = "paneoimg"
        figcaption = bs.new_tag("figcaption")
        figcaption.string = ext.get('caption') 
        img.wrap(figure)
        img.insert_after(figcaption)

    return img

def PaneoImage(k):
    x = GetImageWidth(0)
    if os.path.exists( PANEO_SITE_DATA_DIR + '/_tmp/cache/img/%s_%s' % ( k , x ) ):
        return "/" + PANEO_SITE_DIR + "/_tmp/cache/img/%s_%s" % ( k, x )
    else:
        return "/img/" + k

def GenerateHtmlTemplate( id , bs , page , post ):

    dic = sqlite3dbm.sshelve.open(PANEO_DB)
    scfg = dic.get('siteconfig')
    if not post :
        prefix = "page"
        fields = dic.get('fields')
    else:
        prefix = "post"
        id = post.id
        fields = post.fields
    dic.close()

    #=================================================================================================
    #META
    #=================================================================================================
    if not post:
        if page.get('TITLE') and id != 'index':
            bs.title.string = page.get('TITLE') + ' | ' + scfg.get('SITENAME')
        else:
            bs.title.string = scfg.get('SITENAME')
    else:
        bs.title.string = post.title + ' | ' + scfg.get('SITENAME')

    #=================================================================================================
    #CONTENTS
    #=================================================================================================
    #H* TAG
    for h in bs.find_all(re.compile("h['1','2','3','4','5']")):
        paneo_type = h.get('data-paneo-type')
        paneo_name = h.get('data-paneo-name')
        if paneo_type is not None and paneo_name is not None:
            k = ('txt_%s_%s_%s'%(prefix,id,paneo_name))
            f = fields.get(k)
            if paneo_type == "text" :
                if f :
                    h.string = f.get('string')
  
    #P TAG
    for p in bs.find_all(['p','div','span','article','section']):
        paneo_type = p.get('data-paneo-type')
        paneo_name = p.get('data-paneo-name')
        if paneo_type is not None and paneo_name is not None:
            k = ('txt_%s_%s_%s'%(prefix,id,paneo_name))
            f = fields.get(k)
            if paneo_type == "text" or paneo_type == 'textarea':
                if f :
                    p.string = f.get('string').replace("\r\n","")

    #DIV TAG
    for tag in bs.find_all(['div','span','article','section','dd','li','address']):
        paneo_type = tag.get('data-paneo-type')
        paneo_name = tag.get('data-paneo-name')
        if paneo_type is not None and paneo_name is not None:
            k = ('txt_%s_%s_%s'%(prefix,id,paneo_name))
            f = fields.get(k)
            if paneo_type == "text" or paneo_type == 'textarea':
                if f :
                    tag.string = f.get('string').replace("\r\n","").strip()

    #=================================================================================================
    #IMAGES
    #=================================================================================================
    x = GetImageWidth(0)
    for img in bs.find_all("img"):
        paneo_type = img.get('data-paneo-type')
        paneo_name = img.get("data-paneo-name")
        paneo_max_width = img.get("data-paneo-max-width")
        if paneo_type is not None and paneo_name is not None:
            k = ('img_%s_%s_%s'%(prefix,id,paneo_name))
            f = fields.get(k)
            if f and img:
                ImageTagConvert( k, x , img , f , paneo_max_width , bs )

                

    #=================================================================================================
    #ANCHOR
    #=================================================================================================
    for a in bs.find_all('a'):
        paneo_type = a.get('data-paneo-type')
        paneo_name = a.get('data-paneo-name')
        if paneo_type is not None and paneo_name is not None:
            k = ('a_%s_%s_%s'%(prefix,id,paneo_name))
            f = fields.get(k)
            if paneo_type == "text-link":
                if f :
                    a.string = f.get('string')
                    a['href'] = f.get('ext',{}).get('href')

            if paneo_type == "link-image":
                img = a.find("img")
                paneo_max_width = img.get("data-paneo-max-width")
                if f and img :
                    ImageTagConvert( k, x , img , f , paneo_max_width , bs )

    #=================================================================================================
    #AMAZON
    #=================================================================================================
    amas =  bs.find_all(attrs={'data-paneo-type':'amazon','data-paneo-amazon':'item'})
    for ama in amas:
        paneo_name = ama.get('data-paneo-name')
        title = ama.get('title')
        if paneo_name is not None:
            k = ('ama_%s_%s_%s'%(prefix,id,paneo_name))
            f = fields.get(k)
            if f :
                ext = f.get('ext',{})
                ama_asin = ext.get('asin') 
                itemid = ""
                for ii in range(1,11):
                    asin = ama_asin.get("I:%s"%ii)
                    if asin != "": 
                        itemid = itemid + "%s," % asin

                response = AMAZON_API.ItemLookup(   ItemId=itemid,
                                                    ResponseGroup="Large"   )
                ama_bs = BeautifulSoup(response,fromEncoding="utf8")
                items = []
                for i in ama_bs.findAll("item"):
                    items.append( GetAmazonItem( i ) )
                ama_template = TEMPLATE_DIR+'/include/_aws_item.html'
                if not os.path.exists(ama_template):
                    ama.string = "<div>_aws_item.html not found</div>"
                else:
                    if os.path.exists(PANEO_SITE_DATA_DIR+'_aws_%s.html'%paneo_name) :
                        ama_template = PANEO_SITE_DATA_DIR+'_aws_%s.html'%paneo_name
                    temp = Template(    filename=ama_template, 
                                      output_encoding='utf-8',
                                      input_encoding='utf-8' )
                    
                    PANEO = True
                    ama_html = temp.render( items = items, PANEO = PANEO ) 
                    ama.string = ama_html

    amas =  bs.find_all(attrs={'data-paneo-type':'amazon','data-paneo-amazon':'search'})
    for ama in amas:
        paneo_name = ama.get('data-paneo-name')
        title = ama.get('title')
        if paneo_name is not None:
            k = ('ama_%s_%s_%s'%(prefix,id,paneo_name))
            f = fields.get(k)
            if f :
                ext = f.get('ext',{})
                ama_searchindex = ext.get('searchindex') 
                ama_kw = ext.get('kw') 
                ama_itempage = ext.get('itempage') 
                ama_sort = ext.get('sort') 
                response = AMAZON_API.ItemSearch(   SearchIndex=ama_searchindex,
                                                    Keywords=ama_kw,
                                                    ItemPage=ama_itempage,
                                                    ResponseGroup="Large",
                                                    Sort=ama_sort   )
                ama_bs = BeautifulSoup(response,fromEncoding="utf8")
                items = []
                for i in ama_bs.findAll("item"):
                    items.append( GetAmazonItem( i ) )
                ama_template = TEMPLATE_DIR+'/include/_aws_search.html'
                if not os.path.exists(ama_template):
                    ama.string = "<div>_aws_search.html not found</div>"
                else:
                    if os.path.exists(PANEO_SITE_DATA_DIR+'_aws_%s.html'%paneo_name) :
                        ama_template = PANEO_SITE_DATA_DIR+'_aws_%s.html'%paneo_name
                    temp = Template(    filename=ama_template, 
                                      output_encoding='utf-8',
                                      input_encoding='utf-8' )
                    PANEO = True 
                    ama_html = temp.render( items = items, PANEO = PANEO ) 
                    ama.string = ama_html



    #=================================================================================================
    #OTHER
    #=================================================================================================
    #PAGES Anchor
    bookmark = []
    #b = bs.find_all('a',class_='bookmark')
    for a in bs.find_all('a',attrs={'class':'bookmark'}):
        bookmark.append({'name':a.get('name'),'title':a.get('title')})

    #PANEO TAG REMOVE
    for tag in bs.find_all(attrs={'data-paneo-name':True}):
        del(tag['data-paneo-name'])
        del(tag['data-paneo-type'])
        del(tag['data-paneo-amazon'])
        del(tag['data-paneo-max-width'])
        del(tag['title'])

    for m in bs.find_all(attrs={"name":"paneo-field-text"}):
        m.extract()
    for m in bs.find_all(attrs={"name":"paneo-field-img"}):
        m.extract()

    #MAKE TEMPLATE
    t = unicode(bs)
    #t = t.replace("<head>","\n<head>")
    if not post:
        if id == "index":
            rep_head = '<!-- page css -->\n<link rel="stylesheet" href="//'+web.ctx.host+'/' + id + '.css" media="all"/>\n</head>'
        else:   
            rep_head = '<!-- page css -->\n<link rel="stylesheet" href="//'+web.ctx.host+'/pages/' + id + '.css" media="all"/>\n</head>'
    else:
        rep_head = '<!-- article css -->\n<link rel="stylesheet" href="//'+web.ctx.host+'/common/css/article/' + post.article.type.prefix + '.css" media="all"/>\n</head>'
    t = t.replace("</head>",rep_head)
    t = t.replace("&lt;","<")
    t = t.replace("&gt;",">")
    t = t.replace("&amp;","&")
    t = t.replace("<br>","<br/>")

    return t


#@cache.cache(expire=300)
def GenerateCssTemplate( id , bs , page , post ):

    dic = sqlite3dbm.sshelve.open(PANEO_DB)
    scfg = dic.get('siteconfig')
    if not post :
        prefix = "page"
        fields = dic.get('fields')
    else:
        prefix = "post"
        id = post.id
        fields = post.fields
    dic.close()

    css = "/* PANEO %s CSS */\n" % id 

    #=================================================================================================
    #BACKGROUND
    #=================================================================================================
    for bk in bs.find_all(attrs={'data-paneo-type':'background'}):
        if bk.name == 'body':
            bk_id = 'body'
        else:
            bk_id = bk.get('id')

        paneo_type = 'background'
        paneo_name = "%s_%s" % ( id , bk_id )
        bk_title = bk.get('title')
        bk_url = tag.get('data-paneo-background-url')
        if bk_url is None :
            bk_url = tag.get('data-paneo-url','')

        if bk_id is not None :
            k = ('bk_%s_%s_%s_img'%(prefix,id,bk_id))
            f = fields.get(k)
            f = f.get('ext',{}).get('style',{})

            if bk.name == 'body':
                css = css + ( 'body {\n')
            else:
                css = css + ( bk.name + '#' + bk_id + ' {\n')

            if f :
                bk_src_on = f.get('src_on') 
                bk_size = f.get('size') 
                bk_repeat = f.get('repeat') 
                bk_position = f.get('position') 
                bk_etc = f.get('etc') 
            else:
                bk_src_on = False 
                bk_size = "contain"
                bk_repeat = "no-repeat"
                bk_position = "0 0"
                bk_etc = ""
                
            x = GetImageWidth(0)
                
            if os.path.exists(PANEO_SITE_DATA_DIR+'img/'+k) :
                if bk_src_on == False :
                    if IMG_CONV :
                        if os.path.exists( PANEO_SITE_DATA_DIR + 'cache/img/%s_%s' % ( k, x ) ):
                            bk_url = "/" + PANEO_SITE_DIR + "/cache/img/%s_%s" % ( k, x )
                        else:
                            bk_url = "/img/" + k
                    else:
                        bk_url = "/" + PANEO_SITE_DIR + "/img/" + k
                else:
                    if f :
                        bk_url = f.get('src') 
            else:
                if bk_src_on:
                    bk_url = f.get('src') 

            if bk_url:
                css = css + 'background-image:url(' + bk_url + ');\n'
            if bk_size:
                css = css + 'background-size:' + bk_size + ';\n'
            if bk_repeat:
                css = css + 'background-repeat:' + bk_repeat + ';\n'
            if bk_position:
                css = css + 'background-position:' + bk_position + ';\n'

            if bk_etc :
                css = css + str(bk_etc) + ';\n'

            css = css + '}\n'

    page_css = ""
    #if pages.get(id).get('TEMPLATE_SYSTEM_USE'):
    #    if os.path.exists(PANEO_CMS_PAGE_TEMPLATES_DIR+pages.get(id).get('TEMPLATE')+'.css') :
    #        f_css = codecs.open(PANEO_CMS_PAGE_TEMPLATES_DIR+pages.get(id).get('TEMPLATE')+'.css','r','utf8')
    #        page_css = f_css.read()
    #else:
    if os.path.exists(PANEO_SITE_DATA_DIR+id+'.css'):
        f_css = codecs.open(PANEO_SITE_DATA_DIR+id+'.css',"r","utf8")
        page_css = f_css.read()

    return page_css + "\n" + css 

